package com.atguigu.gulimall.order.config;

import com.atguigu.common.Const.OauthConst;
import com.atguigu.common.vo.MemberEntityVo;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class MyOrderInterceptor implements HandlerInterceptor {
    //同一个线程间共享数据
    public static ThreadLocal<MemberEntityVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        AntPathMatcher pathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        //将/order/order/所有的请求放行（主要出现在在服务间的远程调用的情况下）
        boolean match = pathMatcher.match("/order/order/getOrder", requestURI);
        boolean match1 = pathMatcher.match("/payed/orderNotify", requestURI);
        if (match || match1) {
            return true;
        }

        //session中获取登录后的用户信息
        MemberEntityVo memberEntityVo = (MemberEntityVo) request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
        //已经登陆过了
        if (memberEntityVo != null) {
            threadLocal.set(memberEntityVo);
            return true;
        } else {
            request.getSession().setAttribute("errorMsg", "请先登录");
            //没有登录过，跳转到登录页面
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
